<template>
    <div class="login-container">
        <div class="login-box">
            <h2>{{ isLogin ? '登录' : '注册' }}</h2>
            <form @submit.prevent="handleSubmit">
                <div class="form-group">
                    <input type="text" v-model="username" placeholder="用户名" required />
                </div>
                <div class="form-group">
                    <input type="password" v-model="password" placeholder="密码" required />
                </div>
                <button type="submit">{{ isLogin ? '登录' : '注册' }}</button>
            </form>
            <p class="switch-text">
                {{ isLogin ? '还没有账号？' : '已有账号？' }}
                <a href="#" @click.prevent="isLogin = !isLogin">
                    {{ isLogin ? '立即注册' : '立即登录' }}
                </a>
            </p>
        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const username = ref('')
const password = ref('')
const isLogin = ref(true)

const handleSubmit = async () => {
    try {
        const url = isLogin.value ? '/api/users/login' : '/api/users/register'
        const response = await axios.post(url, {
            username: username.value,
            password: password.value
        })
        if (response.data.token) {
            localStorage.setItem('user', JSON.stringify(response.data))
            router.push('/')
        } else {
            alert(response.data.msg || '登录失败')
        }
    } catch (error) {
        alert(error.response?.data?.msg || JSON.stringify(error.response?.data) || '操作失败')
    }
}
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f5f5f5;
}

.login-box {
    width: 400px;
    padding: 40px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
    text-align: center;
    margin-bottom: 30px;
    color: #333;
}

.form-group {
    margin-bottom: 20px;
}

input {
    width: 100%;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 16px;
}

button {
    width: 100%;
    padding: 12px;
    background-color: #07c160;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
}

button:hover {
    background-color: #06ae56;
}

.switch-text {
    text-align: center;
    margin-top: 20px;
}

a {
    color: #07c160;
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}
</style>